<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		#carousel {
			width: 1000px;
			height: 500px;
			background: #ccc;
			overflow: hidden;
			position: relative;
		}

		.imgs {
			width: 5000px;
			height: 500px;
			position: absolute;
			left: 0;
			transition: all .5s linear;
		}

		.a-img-box {
			width: 1000px;
			height: 500px;
			float: left;
		}
		.a-img-box img {
			width: 100%;
			height: 100%;
		}
	</style>
</head>
<body>
	<div id="carousel">
		<div class="imgs">
			<div class="a-img-box">
				<img class="left-img" src="" alt="">
			</div>
			<div class="a-img-box">
				<img class="the-img" src="" alt="">
			</div>
			<div class="a-img-box">				
				<img class="right-img" src="" alt="">
			</div>
		</div>
	</div>
	<button onclick="preImg()">上一个</button>
	<button onclick="nextImg()">下一个</button>

	<script>
		let arr = ['img/1.jpg','img/2.jpg','img/3.jpg','img/4.jpg','img/5.jpg','img/6.jpg']

		let imgs = document.querySelector('.imgs')
		let leftImg = document.querySelector('.left-img')
		let theImg = document.querySelector('.the-img')
		let rightImg = document.querySelector('.right-img')

		let theIndex = 0
		theImg.src = arr[theIndex]
		leftImg.src = arr[arr.length - 1]
		rightImg.src = arr[1]

		let offset = 1000
		imgs.style.left = `-${offset}px`

		let isDone = true


		function refresh(sign) {
			if(sign === '+') {
				theIndex++
				if(theIndex === arr.length)
					theIndex = 0
			} else if(sign === '-') {
				theIndex--
				if(theIndex === -1) 
					theIndex = arr.length - 1
			}
			console.log('refresh')
			if(theIndex === 0) {
				theImg.src = arr[theIndex]
				leftImg.src = arr[arr.length - 1]
				rightImg.src = arr[1]
				return
			}
			if(theIndex === arr.length - 1) {
				theImg.src = arr[theIndex]
				leftImg.src = arr[theIndex - 1]
				rightImg.src = arr[0]
				return
			}
			theImg.src = arr[theIndex]
			leftImg.src = arr[theIndex - 1]
			rightImg.src = arr[theIndex + 1]
		}

		function preImg() {
			if(isDone === true) {
				isDone = false

				//打开过渡
				imgs.style.transition = 'all .5s linear'
				offset -= 1000
				imgs.style.left = `-${offset}px`

				setTimeout(() => {
					isDone = true
					refresh('-')

					//关掉过渡
					imgs.style.transition = 'all 0s linear'
					//拉到开始
					offset = 1000
					imgs.style.left = `-${offset}px`
					imgs.offsetTop		//强制重绘
				}, 1000)
			}
		}

		//记得加个节流，过渡完成才能再点
		function nextImg() {
			if(isDone === true) {
				isDone = false

				//打开过渡
				imgs.style.transition = 'all .5s linear'
				offset += 1000
				imgs.style.left = `-${offset}px`

				setTimeout(() => {
					isDone = true
					refresh('+')

					//关掉过渡
					imgs.style.transition = 'all 0s linear'
					//拉到开始
					offset = 1000
					imgs.style.left = `-${offset}px`
					imgs.offsetTop		//强制重绘
				}, 1000)
			}
		}

		setInterval(nextImg, 4000)
 	</script>
</body>
</html>